# config_manager.py
import json
import os
from datetime import datetime

CONFIG_FILE = "alarms_config.json"


def load_config():
    """
    从配置文件加载闹钟和铃声设置
    :return: (alarms: list, sound_file: str or None)
    """
    if not os.path.exists(CONFIG_FILE):
        return [], None

    try:
        with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
            alarms = data.get("alarms", [])
            sound_file = data.get("sound_file", None)

            # 确保数据结构完整
            for alarm in alarms:
                if 'type' not in alarm:
                    alarm['type'] = 'fixed'
                if alarm['type'] == 'fixed' and 'triggered_today' not in alarm:
                    alarm['triggered_today'] = False

            return alarms, sound_file
    except Exception as e:
        print(f"❌ 加载配置失败: {e}")
        return [], None


def save_config(alarms, sound_file):
    """
    保存闹钟和铃声设置到配置文件
    :param alarms: 闹钟列表
    :param sound_file: 铃声文件路径
    """
    try:
        # 清理运行时状态字段
        clean_alarms = []
        for alarm in alarms:
            clean_alarm = {
                'type': alarm['type']
            }
            if alarm['type'] == 'fixed':
                clean_alarm['time'] = alarm['time']
            else:
                clean_alarm['minute'] = alarm['minute']

            clean_alarms.append(clean_alarm)

        data = {
            "alarms": clean_alarms,
            "sound_file": sound_file,
            "saved_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "version": "1.0"
        }

        with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

        print(f"✅ 配置已保存至 {CONFIG_FILE}")
    except Exception as e:
        print(f"❌ 保存配置失败: {e}")